<script setup lang="ts">
import { frequencyType } from "@/config/dictionary";
import { zoonType } from "../components/config";
import { deepClone, setLimitCompontentList } from "@/utils";
import PrizePool from "./PrizePool.vue";
import Limits from "@/components/limits/Index.vue";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["change", "update:modelValue"]),
  activityId = inject("activityId", { value: "" }),
  activityBaseInfo: any = inject("activityBaseInfo", {}),
  activityReadonly = inject("activityReadonly");

const form = ref<any>({
    partType: 0,
    freeType: 4,
    partTotalLimit: 0,
  }),
  prizeAreas = ref<Array<any>>([]),
  limitsList = ref<any>();

const formRef = ref(),
  poolRef = ref();

const rules = {
  partTotalNum: [
    { required: true, message: "请输入参与总次数", trigger: "blur" },
  ],
};

const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});

const limitsDisabled = computed(() => {
  return form.value.hasTicket == 1 && activityBaseInfo.value.status == 2;
});

const createPool = (base: any) => {
  let pool: any = {};

  pool = {
    defaulted: base.defaulted,
    type: base.type,
    subType: base.subType,
    pageFlag: form.value.pageFlag,
    name: `${base.defalut ? "默认" : ""}${base.name}`,
    uid: `${form.value.pageFlag}-pool-${prizeAreas.value.length}`,
    prizeInfos: [],
    viewExpression: "",
    viewOriginal:
      base.viewOriginal && typeof base.viewOriginal === "string"
        ? JSON.parse(base.viewOriginal)
        : base.viewOriginal,
  };

  return pool;
};

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);

const formatData = (val: any) => {
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
    partLimit:
      val.pageArea.partLimit && typeof val.pageArea.partLimit === "string"
        ? JSON.parse(val.pageArea.partLimit)
        : [{ type: 1, limitNum: 1 }],
  });

  if (typeof form.value.partExpOriginal === "string") {
    limitsList.value = form.value.partExpOriginal
      ? JSON.parse(form.value.partExpOriginal)
      : {};
  } else limitsList.value = form.value.partExpOriginal || {};

  prizeAreas.value = val.prizeAreas || [];
  // 新建活动初始化奖池
  if (prizeAreas.value.length == 0) {
    for (let i = 0; i < prizePoolType.value.length; i++) {
      prizeAreas.value.push(
        createPool({
          ...prizePoolType.value[i],
        })
      );
    }
  }
  updateData();
};

const updateData = () => {
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
  });
  emits("change");
};

const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: any, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        if (detail.partTotalLimit == 1) {
          detail.freeNum = detail.partTotalNum;
          detail.freeType = 4;
        } else if (detail.partLimit) {
          detail.freeNum = detail.partLimit[0].limitNum;
          detail.freeType = detail.partLimit[0].type;
        } else {
          detail.freeNum = null;
          detail.freeType = null;
        }

        // 限制条件
        if (limitsList.value.children && limitsList.value.children.length > 0)
          detail.partExpOriginal = JSON.stringify(limitsList.value);
        else detail.partExpOriginal = "";

        // 每人参与限制
        if (detail.partLimit)
          detail.partLimit = JSON.stringify(detail.partLimit);
        // 检查每个奖池
        try {
          await poolRef.value.check();
        } catch (e) {
          reject(e);
        }

        resolve({
          pageArea: detail,
          prizeAreas: prizeAreas.value,
        });
      } else {
        formRef.value.scrollToField(Object.keys(invalidFields)[0]);
        reject(`请检查${form.value.name}`);
      }
    });
  });
};

defineExpose({ submit });
</script>
<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    :disabled="activityReadonly || limitsDisabled"
    label-width="auto"
  >
    <h3 class="collpase-title">参与限制</h3>
    <el-form-item label="参与总次数：">
      <el-radio-group v-model="form.partTotalLimit">
        <el-radio :label="0">不限</el-radio>
        <el-radio :label="1">限制</el-radio>
      </el-radio-group>
      <template v-if="form.partTotalLimit == 1">
        <el-form-item label-width="10px" prop="partTotalNum">
          <EasyNumberInput
            v-model="form.partTotalNum"
            :min="1"
            :max="9999"
            :precision="0"
            unit="次"
          />
        </el-form-item>
      </template>
    </el-form-item>
    <el-form-item label="参与次数：">
      <div class="flex-contain" v-for="(limit, index) in form.partLimit">
        每人&nbsp;&nbsp;
        <el-select
          v-model="limit.type"
          placeholder="请选择"
          :disabled="form.type == 3"
          style="width: 100px"
        >
          <el-option
            v-for="(item, key) in frequencyType"
            :label="item"
            :value="Number(key)"
          /> </el-select
        >&nbsp;&nbsp; 最多
        <el-form-item
          label-width="10px"
          :prop="`partLimit.${index}.limitNum`"
          :rules="[
            { required: true, message: '请填写限制次数', trigger: 'blur' },
          ]"
        >
          <EasyNumberInput
            v-model="limit.limitNum"
            :min="1"
            :max="9999"
            unit="次"
            :precision="0"
            :disabled="form.type == 3"
          ></EasyNumberInput>
        </el-form-item>
      </div>
    </el-form-item>
    <el-form-item label="参与条件：">
      <Limits
        v-model="limitsList"
        :disabled="activityReadonly"
        :options="setLimitCompontentList()"
      ></Limits>
    </el-form-item>
  </el-form>
  <PrizePool
    ref="poolRef"
    v-model="prizeAreas"
    :poolType="[2]"
    :poolBaseInfo="prizePoolType"
    :pageFlag="form.pageFlag"
    @change="updateData"
  ></PrizePool>
</template>
<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.flex-contain {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
</style>
